<template>
  <div style="width: 100%;" class="card-area">
    <layout-content topTitle="查询" bottomTitle="订单列表">
      <!-- 搜索区域 -->
      <template v-slot:topCard>
        <search-view ref="searchView" @search="search"/>
      </template>
      <template v-slot:extraOperation>
        <!-- <a-button class="extra-btn" @click="$refs['searchView'].exportFile()">
          导出
        </a-button> -->
      </template>
      <!-- 表格区域 -->
      <template v-slot:bottomCard>
        <a-table
          ref="TableInfo"
          :columns="columns"
          rowKey="id"
          :dataSource="dataSource"
          :loading="loading"
          :scroll="{ x: 1300 }"
          @change="handleTableChange"
          :pagination="pagination"
        >
          <template slot="orderType" slot-scope="text">
            <span>{{ text == 1 ? '仅退款' : '退货退款' }}</span>
          </template>
          <template slot="orderStatus" slot-scope="text">
            <span>{{ orderStatusMap[text] }}</span>
          </template>
          <template slot="operation" slot-scope="text, record">
            <a-button type="link" @click="info(record)" class="icon">详情</a-button>
            <a-button type="link" @click="onReceipt(record)" class="icon" v-if="record.orderStatus == 2 && record.orderType == 2">收货</a-button>
            <a-button type="link" @click="onPay(record)" class="icon" v-if="record.orderStatus == 3">退款</a-button>
            <a-button type="link" @click="onAudit(record, 1)" class="icon" v-if="record.orderStatus == 1">通过</a-button>
            <a-button type="link" @click="onAudit(record, 0)" class="icon" v-if="record.orderStatus == 1">驳回</a-button>
            <a-button type="link" @click="onCompanyInfo(record)" class="icon" v-if="record.orderStatus == 3 && record.orderType == 2">物流信息</a-button>
          </template>
        </a-table>
      </template>
    </layout-content>
    <!-- 查看 -->
    <info-record
      :visible="infoVisible"
      @close="infoVisible = false"
      :initRecord="selectedRecord"
    >
    </info-record>
    <!-- 物流信息 -->
    <logistics-record
      :visible="logisticsVisible"
      @close="logisticsVisible = false"
      :expressItem="expressItem"
    >
    </logistics-record>
  </div>
</template>

<script>
import columns from './columns';
import modal from '~/tool/modal';
import apiURL from './requestURL';
import logisticsRecord from './logistics';
import infoRecord from './info';
import layoutContent from '@/components/tool/layout-content';
import searchView from './search-view';

export default {
  name: 'mainPage',
  components: { layoutContent, modal, searchView, infoRecord, logisticsRecord },
  data() {
    return {
      // 表头
      columns,
      // 接口url
      apiURL,
      // 组件渲染的key
      sendKey: new Date().getTime(),
      // 组件的可见性
      infoVisible: false,
      logisticsVisible: false,
      // 当前选中的记录
      selectedRecord: {},

      dataSource: [],
      sortedInfo: null,
      paginationInfo: null,
      pagination: {
        size: 'small',
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
      loading: false,
      // 0-已取消 1-待商家审核 2-待买家退货 3-待收货(待退款) 4-商家已退款(待退款) 5-商家驳回 6-已完成(退款5天后默认已完成)
      orderStatusMap: Object.freeze({
        '0': '已取消',
        '1': '待审核',
        '2': '待买家退货',
        '3': '待退款(已收货)',
        '4': '已退款',
        '5': '被驳回',
        '6': '已完成'
      }),
      expressItem: {}
    };
  },
  computed: {},
  created() {},
  mounted() {
    this.search();
  },
  methods: {
    // 获取物流信息
    onCompanyInfo(record) {
      let that = this;
      this.selectedRecord = record;
      let tmpObj = {
        no: record.expressNo,
        type: record.expressCompany
      };
      this.$post(this.apiURL.getCompanyInfo, {
        ...tmpObj
      })
        .then(r => {
          that.expressItem = r.data.data;
          that.logisticsVisible = true;
        })
        .catch(() => {});
    },
    // 审核驳回/审核通过
    onAudit(record, tag) {
      let that = this;
      this.$confirm({
        title: tag == 1 ? '确定通过该售后单吗?' : '确定驳回该售后单吗?',
        content: '',
        centered: true,
        onOk() {
          that.$post(apiURL.changeRecords, { id: record.id, orderStatus: tag == 1 ? (record.orderType == 1 ? 3 : 2) : 5 }).then(() => {
            that.$message.success(tag == 1 ? '已通过' : '已驳回');
            that.search(that.params);
          });
        },
        onCancel() {}
      });
    },
    // 确认收货
    onReceipt(record) {
      let that = this;
      this.$confirm({
        title: '确定已经收到货吗?',
        content: '',
        centered: true,
        onOk() {
          that.$post(apiURL.changeRecords, { id: record.id, orderStatus: 3 }).then(() => {
            that.$message.success('收货成功');
            that.search(that.params);
          });
        },
        onCancel() {}
      });
    },
    onPay(record) {
      let that = this;
      console.log(1231)
      this.$confirm({
        title: '确定已经收到货,退款直接到对方账户?',
        content: '',
        centered: true,
        onOk() {
          that.$post(apiURL.refund, { orderNo: record.orderNo}).then(() => {
            console.log(321)
            that.$message.success('退款成功');
            that.search(that.params);
          });
        },
        onCancel() {}
      });
    },
    /**
     * @desc: 查看组件，传入一条记录
     * @param {object} record 当前选择的这条记录
     * @author: youzi
     */
    info(record) {
      this.selectedRecord = record;
      this.infoVisible = true;
    },
    /**
     * @desc: 分页信息改变时的回调函数
     * @param 分页信息，过滤信息，排序信息
     * @author: youzi
     */
    handleTableChange(pagination, filters, sorter) {
      // 将这两个参数赋值给Vue data，用于后续使用
      this.paginationInfo = pagination;
      this.sortedInfo = sorter;
      /* this.fetch({
        sortField: sorter.field,
        sortOrder: sorter.order
      }); */
      // this.$refs['searchView'].handleSearch();
      this.search();
    },
    /**
     * @desc: 调用fetch的入口函数，先拿到当前列的排序和过滤信息
     * @author: youzi
     */
    search(params = {}) {
      let { sortedInfo } = this;
      let sortField, sortOrder;
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field;
        sortOrder = sortedInfo.order;
      }
      this.fetch({
        ...params,
        sortField: sortField,
        sortOrder: sortOrder
      });
    },
    /**
     * @desc: 查询记录的函数
     * @param {object} params 包含查询条件，分页等信息
     * @author: youzi
     */
    fetch(params = {}) {
      this.loading = true;
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current;
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize;
        params.count = this.paginationInfo.pageSize;
        params.currentPage = this.paginationInfo.current;
      } else {
        // 如果分页信息为空，则设置为默认值
        params.count = this.pagination.defaultPageSize;
        params.currentPage = this.pagination.defaultCurrent;
      }
      this.$post(apiURL.getRecords, {
        ...params
      })
        .then(r => {
          let data = r.data.data;
          let pagination = { ...this.pagination };
          pagination.total = data.total;
          var dataSource = [];
          for (var i = 0; i < data.rows.length; i++) {
            let item = data.rows[i];
            let images = item.returnImages || '';
            var imageArr = images.split(',');
            item.images = imageArr;
            dataSource.push(item);
          }
          this.dataSource = dataSource;
          // this.dataSource = data.rows;
          this.pagination = pagination;
          this.loading = false;
        })
        .catch(e => {
          console.error(e);
          this.loading = false;
        });
    }
  }
};
</script>

<style lang="less" scoped>
 .code-img {
  width: 4rem !important;
}
.reject-reason-content {
  text-align: center;
}
.divider {
  margin: 0 4px;
}
.desc {
  font-size: 20px !important;
  color: rgba(0, 0, 0, 0.6);
}
.icon {
  /* svg {
    height: 20px;
    width: 20px;
  } */
  padding: 0;
  border: none;
  color: #1890ff;
}
.card-area {
  .extra-btn {
    width: 86px;
  }
}
.search-btn {
  margin-top: 8px;
}
.border-span {
  width: 2px;
  /* border: 1px solid rgb(207, 215, 222); */
  background-color: #cfd7de;
  height: 16px;
  margin-right: 2px;
  display: inline-block;
}
</style>
